package logic;

import org.apache.log4j.Logger;
import java.util.Calendar;

public class Monitor implements Runnable {
    private NettyClient nettyClient;

    // 日志对象
    private final static Logger logger = Logger.getLogger(Monitor.class);
    // 配置信息
    private final ConfigInfo configInfo = ConfigInfo.getInstance();

    public Monitor(NettyClient nettyClient) {
        this.nettyClient = nettyClient;
    }

    // 当前时间戳
    public static long timestamp = 0;
    
    @Override
    public void run() {
        timestamp = Calendar.getInstance().getTimeInMillis();
        while (true) {
            // 30秒内没有获取心跳,则重连
            long currentStamp = Calendar.getInstance().getTimeInMillis();
            if (currentStamp - timestamp >= configInfo.responseTimeOut) {
                // 物理断开连接,在InActive处进行网络连接
                if (nettyClient != null && nettyClient.getChannel() != null
                        && (!nettyClient.getChannel().isActive()) && (!nettyClient.getChannel().isActive())) {
                    // logger.warn("收到应答数据超时，网络断开连接，尝试连接...");
                    // nettyClient.start();
                } else {
                    logger.warn("网络连接正常,收到应答数据超时...");
                }
            }

            try {
            	// 休眠2秒钟
                Thread.sleep(configInfo.monitorInterval);
            } catch (InterruptedException e) {
            	
            }
        }
    }
}
